import React, { useState, useContext, useEffect } from 'react';
import { Layout, Menu, Avatar, Dropdown, Space, Badge, Button, Tooltip, Modal, List } from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  LogoutOutlined,
  BellOutlined,
  SettingOutlined,
  DashboardOutlined,
  AlertOutlined,
  BuildOutlined,
  VideoCameraOutlined,
  BarChartOutlined,
  AppstoreOutlined,
  ThunderboltOutlined,
  TeamOutlined,
  SafetyOutlined,
  FileTextOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  BulbOutlined,
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import type { MenuProps } from 'antd';
import { ThemeContext } from '../context/ThemeContext';

const { Header, Sider, Content } = Layout;

const BasicLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [isFullscreen, setIsFullscreen] = useState<boolean>(!!document.fullscreenElement);
  const navigate = useNavigate();
  const location = useLocation();
  const { isDark, toggleDark } = useContext(ThemeContext);
  const [isNotificationVisible, setIsNotificationVisible] = useState<boolean>(false);
  type NotificationItem = { id: string; title: string; description: string; time: string; read: boolean };
  const [notifications, setNotifications] = useState<NotificationItem[]>([
    { id: '1', title: '设备告警', description: '电梯 3 号发生故障，已派单处理', time: '2025-11-06 14:32', read: false },
    { id: '2', title: '系统提醒', description: '每日数据库备份完成', time: '2025-11-06 02:10', read: true },
    { id: '3', title: '任务进度', description: '空调巡检任务已完成 80%', time: '2025-11-05 18:45', read: false },
    { id: '4', title: '消息通知', description: '新用户已加入系统：张三', time: '2025-11-05 09:12', read: true }
  ]);
  const [selectedNotification, setSelectedNotification] = useState<NotificationItem | null>(null);
  const unreadCount = notifications.filter(n => !n.read).length;
  const openNotifications = () => setIsNotificationVisible(true);
  const closeNotifications = () => setIsNotificationVisible(false);
  const markAllRead = () => setNotifications(prev => prev.map(n => ({ ...n, read: true })));
  const clearNotifications = () => setNotifications([]);
  const markItemRead = (id: string) => setNotifications(prev => prev.map(n => (n.id === id ? { ...n, read: true } : n)));
  const openNotificationDetail = (item: NotificationItem) => setSelectedNotification(item);
  const closeNotificationDetail = () => setSelectedNotification(null);

  useEffect(() => {
    const handleFsChange = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener('fullscreenchange', handleFsChange);
    return () => document.removeEventListener('fullscreenchange', handleFsChange);
  }, []);

  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen?.().catch(() => {});
    } else {
      document.exitFullscreen?.();
    }
  };

  // 菜单项配置
  const menuItems: MenuProps['items'] = [
    {
      key: '/dashboard',
      icon: <DashboardOutlined />,
      label: '仪表盘',
    },
    {
      key: '/dashboard-3d',
      icon: <ThunderboltOutlined />,
      label: '3D看板',
    },
    {
      key: '/alarm',
      icon: <AlertOutlined />,
      label: '报警管理',
      children: [
        { key: '/alarm/list', label: '报警列表' },
        { key: '/alarm/statistics', label: '报警统计' },
        { key: '/alarm/rules', label: '报警规则' },
      ],
    },
    {
      key: '/subsystem',
      icon: <BuildOutlined />,
      label: '子系统管理',
      children: [
        { key: '/subsystem/list', label: '子系统列表' },
        { key: '/subsystem/elevator', label: '电梯系统' },
        { key: '/subsystem/hvac', label: '暖通空调' },
        { key: '/subsystem/parking', label: '停车系统' },
      ],
    },
    {
      key: '/equipment',
      icon: <VideoCameraOutlined />,
      label: '设备管理',
      children: [
        { key: '/equipment/list', label: '设备列表' },
        { key: '/equipment/monitor', label: '设备监控' },
      ],
    },
    {
      key: '/statistics',
      icon: <BarChartOutlined />,
      label: '统计分析',
      children: [
        { key: '/statistics/overview', label: '数据概览' },
        { key: '/statistics/report', label: '报表中心' },
      ],
    },
    {
      key: '/user',
      icon: <TeamOutlined />,
      label: '用户管理',
      children: [
        { key: '/user/list', label: '用户列表' },
        { key: '/user/roles', label: '角色管理' },
      ],
    },
    {
      key: '/system',
      icon: <SafetyOutlined />,
      label: '系统管理',
      children: [
        { key: '/system/settings', label: '系统设置' },
        { key: '/system/logs', label: '系统日志' },
      ],
    },
  ];

  // 用户下拉菜单
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人中心',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '个人设置',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
    },
  ];

  // 处理菜单点击
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    navigate(key);
  };

  // 处理用户菜单点击
  const handleUserMenuClick: MenuProps['onClick'] = ({ key }) => {
    if (key === 'logout') {
      localStorage.removeItem('rememberMe');
      localStorage.removeItem('username');
      navigate('/login');
    } else if (key === 'profile') {
      navigate('/profile');
    } else if (key === 'settings') {
      navigate('/settings');
    }
  };

  // 收集所有菜单 key 以精确匹配选中项
  const allMenuKeys: string[] = (menuItems || []).flatMap((item: any) => {
    if (item?.children) {
      return [item.key, ...item.children.map((c: any) => c.key)];
    }
    return [item.key];
  });

  // 获取当前选中的菜单项（优先高亮具体子菜单）
  const getSelectedKeys = () => {
    const path = location.pathname;
    if (allMenuKeys.includes(path)) return [path];
    return [];
  };

  // 根据路径控制展开的父级菜单
  React.useEffect(() => {
    const path = location.pathname;
    if (collapsed) {
      setOpenKeys([]);
      return;
    }
    // 查找父级 key
    const parent = (menuItems || []).find((item: any) => item?.children?.some((c: any) => c.key === path));
    if (parent?.key) {
      setOpenKeys([parent.key as string]);
    } else {
      setOpenKeys([]);
    }
  }, [location.pathname, collapsed]);

  // 生成顶部导航文字（父级/子级）
  const getPageNavText = () => {
    const path = location.pathname;
    const items = (menuItems || []) as any[];
    const direct = items.find((i) => i.key === path);
    if (direct) {
      const label = direct.label;
      return typeof label === 'string' ? label : '当前页面';
    }
    const parent = items.find((i) => i.children?.some((c: any) => c.key === path));
    if (parent) {
      const child = parent.children.find((c: any) => c.key === path);
      const pLabel = typeof parent.label === 'string' ? parent.label : '分组';
      const cLabel = child ? (typeof child.label === 'string' ? child.label : '子页面') : '';
      return `${pLabel} / ${cLabel}`;
    }
    // 根或未匹配路径
    return '首页';
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider 
        trigger={null} 
        collapsible 
        collapsed={collapsed}
        style={{
          overflow: 'auto',
          height: '100vh',
          position: 'fixed',
          left: 0,
          top: 0,
          bottom: 0,
        }}
      >
        <div className="logo" style={{ 
          height: 64, 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'flex-start',
          margin: '16px',
          padding: '8px 16px',
          boxSizing: 'border-box',
          background: 'rgba(255, 255, 255, 0.1)',
          borderRadius: '8px',
          gap: '12px'
        }}>
          <img 
            src="/logo_huafa.svg" 
            alt="IBMS Logo" 
            style={{ 
              width: collapsed ? '32px' : '48px', 
              height: collapsed ? '32px' : '48px', 
              objectFit: 'contain',
              transition: 'all 0.3s ease'
            }} 
          />
          <div style={{ 
            display: collapsed ? 'none' : 'flex',
            flexDirection: 'column',
            color: 'white',
            flex: 1,
            minWidth: 0
          }}>
            <div style={{ 
              fontSize: '18px', 
              fontWeight: 'bold',
              lineHeight: '1.3',
              marginBottom: '4px',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            }}>
              IBMS
            </div>
            <div style={{ 
              fontSize: '12px', 
              opacity: '0.8',
              lineHeight: '1.2'
            }}>
              智慧楼宇管理系统
            </div>
          </div>
        </div>
        
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={getSelectedKeys()}
          openKeys={openKeys}
          onOpenChange={(keys) => setOpenKeys(keys as string[])}
          items={menuItems}
          onClick={handleMenuClick}
          style={{ borderRight: 0 }}
        />
      </Sider>
      
      <Layout style={{ marginLeft: collapsed ? 80 : 200 }}>
        <Header 
          style={{ 
            padding: '0 24px', 
            background: '#fff', 
            display: 'flex', 
            alignItems: 'center',
            justifyContent: 'space-between',
            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
            zIndex: 1
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              style={{
                fontSize: '16px',
                width: 64,
                height: 64,
              }}
            />
            <span style={{
              fontSize: '16px',
              fontWeight: 500,
              color: '#333'
            }}>
              {getPageNavText()}
            </span>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
              <Button
                type="text"
                icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                onClick={toggleFullscreen}
                style={{ fontSize: 18 }}
              />
            </Tooltip>
            <Tooltip title={isDark ? '切换到日间模式' : '切换到黑夜模式'}>
              <Button
                type="text"
                icon={<BulbOutlined />}
                onClick={toggleDark}
                style={{ fontSize: 18 }}
              />
            </Tooltip>
            <Badge count={unreadCount} size="small">
              <Button type="text" icon={<BellOutlined />} onClick={openNotifications} style={{ fontSize: 18 }} />
            </Badge>
            
            <Dropdown
              menu={{ items: userMenuItems, onClick: handleUserMenuClick }}
              placement="bottomRight"
              arrow
            >
              <Space style={{ cursor: 'pointer' }}>
                <Avatar size="small" icon={<UserOutlined />} />
                <span>管理员</span>
              </Space>
            </Dropdown>
          </div>
        </Header>
        
        <Content 
          style={{ 
            margin: '24px', 
            padding: '24px', 
            background: '#fff',
            borderRadius: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
            minHeight: 'calc(100vh - 112px)',
            overflow: 'auto'
          }}
        >
          <Outlet />
        </Content>
        <Modal
          title="消息提醒"
          open={isNotificationVisible}
          onCancel={closeNotifications}
          footer={[
            <Button key="read" onClick={markAllRead}>全部已读</Button>,
            <Button key="clear" danger onClick={clearNotifications}>清空</Button>,
          ]}
          width={560}
          destroyOnHidden
        >
          <List
            itemLayout="horizontal"
            dataSource={notifications}
            locale={{ emptyText: '暂无消息' }}
            renderItem={(item) => (
              <List.Item
                actions={[
                  !item.read ? (
                    <Button type="link" onClick={() => markItemRead(item.id)} key="mark">标记已读</Button>
                  ) : null,
                  <Button type="link" onClick={() => openNotificationDetail(item)} key="detail">查看详情</Button>,
                ]}
              >
                <List.Item.Meta
                  title={
                    <span>
                      {item.title} {!item.read && <Badge dot style={{ marginLeft: 8 }} />}
                    </span>
                  }
                  description={item.description}
                />
                <div style={{ color: '#999' }}>{item.time}</div>
              </List.Item>
            )}
          />
        </Modal>
        <Modal
          title={selectedNotification ? `消息详情 - ${selectedNotification.title}` : '消息详情'}
          open={!!selectedNotification}
          onCancel={closeNotificationDetail}
          footer={[
            <Button key="close" onClick={closeNotificationDetail}>关闭</Button>,
            selectedNotification && !selectedNotification.read ? (
              <Button 
                key="read" 
                type="primary" 
                onClick={() => {
                  if (selectedNotification) {
                    markItemRead(selectedNotification.id);
                    closeNotificationDetail();
                  }
                }}
              >标记已读</Button>
            ) : null,
          ]}
          width={600}
          destroyOnHidden
        >
          {selectedNotification && (
            <div style={{ lineHeight: 1.8 }}>
              <div style={{ marginBottom: 8 }}>
                <strong>标题：</strong>{selectedNotification.title}
              </div>
              <div style={{ marginBottom: 8 }}>
                <strong>时间：</strong>{selectedNotification.time}
              </div>
              <div style={{ whiteSpace: 'pre-wrap' }}>
                <strong>内容：</strong>{selectedNotification.description}
              </div>
            </div>
          )}
        </Modal>
      </Layout>
    </Layout>
  );
};

export default BasicLayout;